package com.jianbing.util;

import com.jianbing.http.HttpAsynClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class IpCheckUtils {
    private static Log log = LogFactory.getLog(IpCheckUtils.class);

    public static void main(String[] args) throws Exception {
        String ip = "60.21.209.114";
        int port = 8080;
        checkValid("http://www.baidu.com", ip, port);
    }

    public void useProxy() {
        System.setProperty("http.proxyHost", "www.proxy.com");
        System.setProperty("http.proxyPort", "8080");
    }


    public static boolean checkValid(String httpUrl, String proxyIp, int proxyPort) {
        try {
            HttpAsynClient.doGet(httpUrl, proxyIp, proxyPort);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 用proxyIp和proxyPort来检查给定httpUrl是否可以访问
     *
     * @param httpUrl
     * @param proxyIp
     * @param proxyPort
     */
    private static boolean createIPAddress(String httpUrl, String proxyIp, int proxyPort) throws Exception {
        URL url = null;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e) {
            throw e;
        }
        InetSocketAddress addr = new InetSocketAddress(proxyIp, proxyPort);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); // http proxy
        InputStream in = null;
        URLConnection conn = null;
        try {
            conn = url.openConnection(proxy);
            conn.setConnectTimeout(60000000);
            in = conn.getInputStream();
            String s = convertStreamToString(in);
        } catch (Exception e) {
            log.info("ip " + proxyIp + " is not aviable");
            return false;
        }
        return true;
    }

    private static String convertStreamToString(InputStream is) {
        if (is == null)
            return "";
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "/n");
            }
        } catch (IOException e) {
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
        return sb.toString();

    }
}